package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import com.mes.cloud.api.dto.request.area.BatchDeleteSaleStrategyRequest;
import com.mes.cloud.api.dto.request.area.BindSaleStrategyRequest;
import com.mes.cloud.api.dto.request.area.OrgSaleStrategyPageListRequest;
import com.mes.cloud.api.dto.request.area.SaleStrategyPageListRequest;
import com.mes.cloud.api.dto.request.product.ProductSaleStrategyPageListRequest;
import com.mes.cloud.api.dto.request.product.SaleStrategyCustomerProductListRequest;
import com.mes.cloud.api.dto.response.area.OrgSaleStrategyDto;
import com.mes.cloud.api.dto.response.area.SaleStrategyDto;
import com.mes.cloud.api.dto.response.product.ProductSaleStrategyDto;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.BaseAreaDao;
import com.mes.cloud.dao.BaseAreaSaleStrategyDao;
import com.mes.cloud.dao.ProductDirectoryDao;
import com.mes.cloud.dao.SysOrganizationChannelDao;
import com.mes.cloud.entity.BaseArea;
import com.mes.cloud.entity.BaseAreaSaleStrategy;
import com.mes.cloud.entity.SysAreaLog;
import com.mes.cloud.entity.SysOrganizationChannel;
import com.mes.cloud.entity.vo.ProductDirectoryVo;
import com.mes.cloud.entity.vo.area.BaseAreaSaleProductVo;
import com.mes.cloud.entity.vo.area.SaleStrategyVo;
import com.mes.cloud.entity.vo.organization.SysOrganizationChannelVo;
import com.mes.cloud.entity.vo.product.ProductSaleStrategyVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dongyi
 * @description 区域产品分销策略
 * @date 2019-08-22 11:54
 **/
@Service
public class BaseAreaSaleStrategyService {

    private BaseAreaSaleStrategyDao baseAreaSaleStrategyDao;

    private ProductDirectoryDao productDirectoryDao;

    private IPKeyGenerator iPKeyGenerator;

    private LogService logService;

    private BaseAreaDao baseAreaDao;

    private SysOrganizationChannelDao sysOrganizationChannelDao;

    @Autowired
    public BaseAreaSaleStrategyService(BaseAreaSaleStrategyDao baseAreaSaleStrategyDao,
                                       IPKeyGenerator iPKeyGenerator,
                                       LogService logService,
                                       ProductDirectoryDao productDirectoryDao,BaseAreaDao baseAreaDao,
                                       SysOrganizationChannelDao sysOrganizationChannelDao) {
        this.baseAreaSaleStrategyDao = baseAreaSaleStrategyDao;
        this.productDirectoryDao = productDirectoryDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.logService = logService;
        this.baseAreaDao = baseAreaDao;
        this.sysOrganizationChannelDao = sysOrganizationChannelDao;
    }

    /**
     * 分页查列表
     *
     * @param pageRequest
     * @return JsonResult
     */
    public JsonResult<CommPager<SaleStrategyDto>> pageList(SaleStrategyPageListRequest pageRequest) {
        Page<SaleStrategyDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("areaId", pageRequest.getAreaId());
        params.put("queryString", pageRequest.getQueryString());
        List<SaleStrategyVo> baseAreaSaleStrategyList = baseAreaSaleStrategyDao.selectSaleStrategy(params);
        List<SaleStrategyDto> baseAreaSaleStrategyDtoList = new ArrayList<>();
        for (SaleStrategyVo saleStrategyVo : baseAreaSaleStrategyList) {
            // 查询品牌
            if(!StringUtils.isEmpty(saleStrategyVo.getProductDirectoryId())){
                ProductDirectoryVo productDirectory= productDirectoryDao.selectProductDirectoryDetails(saleStrategyVo.getProductDirectoryId());
                saleStrategyVo.setBrandName(productDirectory.getBrandName());
            }
            SaleStrategyDto saleStrategyDto = new SaleStrategyDto();
            BeanUtils.copyProperties(saleStrategyVo, saleStrategyDto);
            baseAreaSaleStrategyDtoList.add(saleStrategyDto);
        }
        CommPager<SaleStrategyDto> pageResult = new CommPager<>(page, baseAreaSaleStrategyDtoList);
        JsonResult<CommPager<SaleStrategyDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 根据组织查找产品分销策略
     *
     * @param pageRequest
     * @return JsonResult
     */
    public JsonResult<CommPager<OrgSaleStrategyDto>> orgPageList(OrgSaleStrategyPageListRequest pageRequest) {
        JsonResult<CommPager<OrgSaleStrategyDto>> jsonResult = new JsonResult<>();
        // 查询组织的所属渠道
        SysOrganizationChannel sysOrganizationChannel = new SysOrganizationChannel();
        sysOrganizationChannel.setOrganizationId(pageRequest.getOrganizationId());
        List<SysOrganizationChannelVo> organizationChannelList = sysOrganizationChannelDao.findAllByOragId(sysOrganizationChannel);
        // 如果组织没有查到所属渠道，也就没有产品分销策略，直接返回
        if(CollectionUtils.isEmpty(organizationChannelList)){
            CommPager<OrgSaleStrategyDto> pageResult = new CommPager<>();
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
            return jsonResult;
        }

        //从list中拼接channle_id
        List<String> channleIdList = organizationChannelList.stream().map(SysOrganizationChannelVo::getChannelId).collect(Collectors.toList());
        String channleIds = String.join(",",channleIdList);

        Page<SaleStrategyDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("organizationId", pageRequest.getOrganizationId());
        params.put("channleIds", channleIds);
        params.put("queryString", pageRequest.getQueryString());
        List<SaleStrategyVo> baseAreaSaleStrategyList = baseAreaSaleStrategyDao.selectOrgSaleStrategy(params);
        List<OrgSaleStrategyDto> baseAreaSaleStrategyDtoList = new ArrayList<>();
        for (SaleStrategyVo saleStrategyVo : baseAreaSaleStrategyList) {
            // 设置行政区划全名
            BaseArea bArea = baseAreaDao.selectByPrimaryKey(saleStrategyVo.getAreaId());
            String areaFullName = baseAreaDao.getAreaFullName(bArea.getParentGroup() + "," + bArea.getId());
            saleStrategyVo.setAreaName(areaFullName);
            OrgSaleStrategyDto saleStrategyDto = new OrgSaleStrategyDto();
            BeanUtils.copyProperties(saleStrategyVo, saleStrategyDto);
            baseAreaSaleStrategyDtoList.add(saleStrategyDto);
        }
        CommPager<OrgSaleStrategyDto> pageResult = new CommPager<>(page, baseAreaSaleStrategyDtoList);
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 新增关联-产品分销策略
     *
     * @param bindSaleStrategyRequest
     * @return JsonResult
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult bindSaleStrategy(BindSaleStrategyRequest bindSaleStrategyRequest) {
        JsonResult jsonResult = new JsonResult();
        BaseAreaSaleStrategy baseAreaSaleStrategy = new BaseAreaSaleStrategy();
        BeanUtils.copyProperties(bindSaleStrategyRequest, baseAreaSaleStrategy);

        // 查询该行政区划、该产品、该渠道、该门店等级下是否已有分销策略
        BaseAreaSaleStrategy duplicate = new BaseAreaSaleStrategy();
        duplicate.setAreaId(bindSaleStrategyRequest.getAreaId());
        duplicate.setProductId(bindSaleStrategyRequest.getProductId());
        duplicate.setChannelId(bindSaleStrategyRequest.getChannelId());
        duplicate.setStoreGrade(bindSaleStrategyRequest.getStoreGrade());
        duplicate.setDelFlag(Constants.DEL_FLAG_NO);
        duplicate.setEnableFlag(Constants.ENABLE_FLAG_YES);
        int bindCount = baseAreaSaleStrategyDao.selectCount(duplicate);
        if (bindCount > 0) {
            return jsonResult.setCode(HttpStatusEnum.REF_EXIST.getCode()).setMsg(HttpStatusEnum.REF_EXIST.getMessage());
        }
        baseAreaSaleStrategy.setId(iPKeyGenerator.getGenerateKey());
        baseAreaSaleStrategy.setUpdateDateStr(DateUtil.updateDateStr());
        baseAreaSaleStrategy.setCreateBy(UserUtil.getCreateByName());
        baseAreaSaleStrategy.setUpdateBy(UserUtil.getUpdateByName());
        baseAreaSaleStrategy.setCreateByNo(UserUtil.getCreateByNo());
        baseAreaSaleStrategy.setUpdateByNo(UserUtil.getUpdateByNo());
        // 插入数据
        int count = baseAreaSaleStrategyDao.insertSelective(baseAreaSaleStrategy);
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            BaseArea baseArea = new BaseArea();
            baseArea.setId(baseAreaSaleStrategy.getAreaId());
            this.insertLog(baseArea, Constants.ADD_LINK_TO_SALE_STRATEGY);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 批量移除关联关系
     *
     * @param batchDeleteSaleStrategyRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult batchDelete(BatchDeleteSaleStrategyRequest batchDeleteSaleStrategyRequest) {
        JsonResult jsonResult = new JsonResult();
        int count = baseAreaSaleStrategyDao.batchDeleteSaleStrategy(batchDeleteSaleStrategyRequest.getIds(),
                DateUtil.updateDateStr(), UserUtil.getName(),UserUtil.getEmployeeNo());
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            BaseArea baseArea = new BaseArea();
            baseArea.setId(batchDeleteSaleStrategyRequest.getAreaId());
            this.insertLog(baseArea, Constants.REMOVE_LINK_TO_SALE_STRATEGY);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(),HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * @description 添加操作日志
     * @author dongyi
     * @date 2019-08-07 13:36
     **/
    @SuppressWarnings("Duplicates")
    private int insertLog(BaseArea baseArea, String logMessage) {
        SysAreaLog sysAreaLog = new SysAreaLog();
        sysAreaLog.setAreaId(baseArea.getId());
        sysAreaLog.setMenuCode(Constants.AREA_MENU_CODE);
        sysAreaLog.setLog(logMessage);
        sysAreaLog.setId(iPKeyGenerator.getGenerateKey());
        sysAreaLog.setUpdateDateStr(DateUtil.updateDateStr());
        sysAreaLog.setCreateBy(UserUtil.getCreateByName());
        sysAreaLog.setUpdateBy(UserUtil.getUpdateByName());
        sysAreaLog.setCreateByNo(UserUtil.getCreateByNo());
        sysAreaLog.setUpdateByNo(UserUtil.getUpdateByNo());
        return logService.insertAreaLog(sysAreaLog);
    }

    /**
     * <产品分销策略分页查列表>
     *
     * @param pageRequest
     * @return JsonResult<CommPager<ProductSaleStrategyDto>>
     * @author xy
     * @date 2019/8/30 16:52
     */
    public JsonResult<CommPager<ProductSaleStrategyDto>> productSaleStrategyPageList(ProductSaleStrategyPageListRequest pageRequest) {
        Page<SaleStrategyDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());

        List<ProductSaleStrategyVo> productSaleStrategyList = baseAreaSaleStrategyDao.selectProductSaleStrategy(pageRequest);
        List<ProductSaleStrategyDto> baseAreaSaleStrategyDtoList = new ArrayList<>();
        for (ProductSaleStrategyVo saleStrategyVo : productSaleStrategyList) {
            ProductSaleStrategyDto saleStrategyDto = new ProductSaleStrategyDto();
            BeanUtils.copyProperties(saleStrategyVo, saleStrategyDto);
            baseAreaSaleStrategyDtoList.add(saleStrategyDto);
        }

        CommPager<ProductSaleStrategyDto> pageResult = new CommPager<>(page, baseAreaSaleStrategyDtoList);
        JsonResult<CommPager<ProductSaleStrategyDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);

        return jsonResult;
    }

    /**
     * @Author ysd
     * @Description 合作关系（cash）_ 导入分销策略_可售、必售产品
     * @Date 17:11 2019/9/23
     **/
    public JsonResult<List<ProductSaleStrategyDto>> selectCustomerProductByCostomer(SaleStrategyCustomerProductListRequest pageRequest) {
        JsonResult<List<ProductSaleStrategyDto>> jsonResult = new JsonResult<>();

        List<BaseAreaSaleProductVo> baseAreaSaleProductVos = baseAreaSaleStrategyDao.selectCustomerProductByCostomer(pageRequest);
        List<ProductSaleStrategyDto> baseAreaSaleStrategyDtoList = new ArrayList<>();
        for (BaseAreaSaleProductVo saleStrategyVo : baseAreaSaleProductVos) {
            ProductSaleStrategyDto saleStrategyDto = new ProductSaleStrategyDto();
            BeanUtils.copyProperties(saleStrategyVo, saleStrategyDto);
            baseAreaSaleStrategyDtoList.add(saleStrategyDto);
        }
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaSaleStrategyDtoList);
        return jsonResult;
    }
}
